package ldh.im.fxgui.pane;

import javafx.beans.InvalidationListener;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.concurrent.Worker;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.web.PopupFeatures;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import ldh.im.dto.enums.MessageType;
import ldh.im.fxbase.data.pojo.ImMessage;

import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

public class HtmlMessagePane extends BaseMessagePane {

    private volatile AtomicBoolean isLoad = new AtomicBoolean(false);

    @Override
    public Node createPane(ImMessage message, boolean isReceive, boolean isRef) {
        if (message.getMessageType() != MessageType.Html) {
            throw new RuntimeException("不支持这种消息类型" + message.getMessageType());
        }

        WebView webView = new WebView();
        webView.getEngine().loadContent(message.getContent());
        bindEventWebView(webView);
        return webView;
    }

    private void bindEventWebView(WebView webView) {
        webView.getChildrenUnmodifiable().addListener(new ListChangeListener<Node>() {
            @Override public void onChanged(Change<? extends Node> change) {
                Set<Node> deadSeaScrolls = webView.lookupAll(".scroll-bar");
                for (Node scroll : deadSeaScrolls) {
                    scroll.setVisible(false);
                }
            }
        });


        webView.getEngine().getLoadWorker().stateProperty().addListener(
                new ChangeListener<Worker.State>() {
                    @Override
                    public void changed(ObservableValue<? extends Worker.State> ov, Worker.State oldState, Worker.State newState) {
                        if (newState == Worker.State.SUCCEEDED) {
                            if (isLoad.get()) return;
                            String js = "Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);";
                            Object dd = webView.getEngine().executeScript(js);
                            if (dd == null) return;
                            double d = Double.parseDouble(dd.toString());
                            if (d == 60.0d) d = 40d;
                            webView.setPrefHeight(d);
                            webView.setMinHeight(d);
                            webView.setMaxHeight(d);
//                            isLoad = true;
                            isLoad.set(true);
                        }
                    }
                }
        );

        webView.getEngine().setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() {

            @Override
            public WebEngine call(PopupFeatures p) {
                Stage stage = new Stage(StageStyle.UTILITY);
                WebView wv2 = new WebView();
                stage.setScene(new Scene(wv2));
                stage.show();
                return wv2.getEngine();
            }
        });

        webView.focusedProperty().addListener((InvalidationListener) l->{
            if (!webView.focusedProperty().get()) {
                try{
                    webView.getEngine().executeScript("cleanSelection()");
                } catch (Exception e) {}
            }
        });
//        this.focusedProperty().addListener(e->webView.requestFocus());
    }

}
